/**   
 * All rights Reserved, Designed By MiGu  
 * Copyright:    Copyright(C) 2016-2020  
 * Company       MiGu  Co., Ltd.
*/
package com.migu.spms.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.migu.spms.common.StringUtil;
import com.migu.spms.dao.entity.ChangeHistoryCriteria;
import com.migu.spms.dao.entity.ChangeHistoryDO;
import com.migu.spms.dao.entity.FunctionRequireDO;
import com.migu.spms.dao.inf.IChangeHistoryDO;
import com.migu.spms.dao.inf.IFunctionRequireDO;
import com.migu.spms.service.data.FunctionRequireCompare;
import com.migu.spms.service.inf.IChangeHistoryService;
import com.migu.spms.utils.PropertiesCopyUtil;
import com.migu.spms.utils.RequireCompareUtil;
import com.migu.spms.webapi.data.BaselineResponse;
import com.migu.spms.webapi.data.ChangeHistoryResponse;


/**   
 * ChangeHistoryServiceImpl类
 * 项目名称:  SPMS功能需求
 * 包名称:    com.migu.spms.service.impl   
 * 类名称:    ChangeHistoryServiceImpl.java
 * 类描述:    变更历史接口
 * 创建人:    wcr   
 * 创建时间:  2017年6月21日 上午10:25:31   
 */
@Transactional
@Service("changeHistoryServiceImpl")
public class ChangeHistoryServiceImpl implements IChangeHistoryService {

    private static Logger logger = LoggerFactory.getLogger(ChangeHistoryServiceImpl.class);
	private static SimpleDateFormat formate=new SimpleDateFormat("yyyy-MM-dd");

    @Resource(name = "IChangeHistoryDO")
    private IChangeHistoryDO changeHistoryDO;
    
    @Resource(name="IFunctionRequireDO")
    private IFunctionRequireDO functionRequireDAO;
    
    @Override
    public void inesertChangeHistoryCommon(ChangeHistoryCriteria criteria, FunctionRequireCompare compareOld, 
            FunctionRequireCompare compareNew) throws Exception {
        List<ChangeHistoryCriteria> changeList = new ArrayList<ChangeHistoryCriteria>();
        if(null != compareOld && null != compareNew){
            List<Map<String, Object>> compareList = RequireCompareUtil.compareTwoClass(compareOld, compareNew);
            if(null != compareList && compareList.size() > 0){
                for (Map<String, Object> map : compareList) {
                    ChangeHistoryCriteria obj = compareFileds(criteria, map);
                    if("===修改前：空".equals(obj.getBeforePermit())
                    		&& "===修改后：空".equals(obj.getAfterPermit())){
                    	//修改前后都为空（即使是特殊值转变的空），则不插入任何历史记录
                    }else{                    	
                    	changeList.add(obj);
                    }
                }
            }
        }else{
            changeList.add(criteria);
        }
        if(changeList.size()>0){
        	changeHistoryDO.insertChangeHistoryBatch(changeList);
        }
    }

    /**
    * 
    * @param criteria
    * @param map
     * @throws ParseException 
    * @exception
    * @throws
    */
    private ChangeHistoryCriteria compareFileds(ChangeHistoryCriteria obj, Map<String, Object> map) throws ParseException {
        ChangeHistoryCriteria criteria = PropertiesCopyUtil.copy(obj, ChangeHistoryCriteria.class);
        if(map.containsValue("projectId")){
            criteria.setBeforePermit(map.get("old").toString());
            criteria.setAfterPermit(map.get("new").toString());
            criteria.setRemark("项目ID：" + criteria.getBeforePermit() + criteria.getAfterPermit());
        }else if(map.containsValue("requireName")){
            criteria.setBeforePermit(map.get("old").toString());
            criteria.setAfterPermit(map.get("new").toString());
            criteria.setRemark("需求名称：" + criteria.getBeforePermit() + criteria.getAfterPermit());
        }else if(map.containsValue("requireTypeName")){
            criteria.setBeforePermit(map.get("old").toString());
            criteria.setAfterPermit(map.get("new").toString());
            criteria.setRemark("需求类别名称：" + criteria.getBeforePermit() + criteria.getAfterPermit());
        }else if(map.containsValue("expectFinishTime")){    
        	
        	this.handleDate(map,criteria);//时间格式特殊处理
        	
            criteria.setRemark("开发计划完成时间：" + criteria.getBeforePermit() + criteria.getAfterPermit());
        }else if(map.containsValue("expectStartTime")){
        	
        	this.handleDate(map,criteria);//时间格式特殊处理
        	
            criteria.setRemark("开发计划开始时间：" + criteria.getBeforePermit() + criteria.getAfterPermit());
        }else if(map.containsValue("priorityRank")){
            criteria.setBeforePermit(map.get("old").toString());
            criteria.setAfterPermit(map.get("new").toString());
            criteria.setRemark("优先级：" + criteria.getBeforePermit() + criteria.getAfterPermit());
        }else if(map.containsValue("relativeBusinessRequireName")){
            criteria.setBeforePermit(map.get("old").toString());
            criteria.setAfterPermit(map.get("new").toString());
            criteria.setRemark("业务需求名称：" + criteria.getBeforePermit() + criteria.getAfterPermit());
        }else if(map.containsValue("baselineVersion")){
            criteria.setBeforePermit(map.get("old").toString());
            criteria.setAfterPermit(map.get("new").toString());
            criteria.setRemark("基线版本：" + criteria.getBeforePermit() + criteria.getAfterPermit());
        }else if(map.containsValue("estimateWorkload")){
            criteria.setBeforePermit(map.get("old").toString());
            criteria.setAfterPermit(map.get("new").toString());
            criteria.setRemark("预估开发工作量：" + criteria.getBeforePermit() + criteria.getAfterPermit());
        }else if(map.containsValue("parentId")){
            criteria.setBeforePermit(map.get("old").toString());
            criteria.setAfterPermit(map.get("new").toString());
            criteria.setRemark("父需求id：" + criteria.getBeforePermit() + criteria.getAfterPermit());
        }else if(map.containsValue("creatorName")){
            criteria.setBeforePermit(map.get("old").toString());
            criteria.setAfterPermit(map.get("new").toString());
            criteria.setRemark("创建人姓名：" + criteria.getBeforePermit() + criteria.getAfterPermit());
        }else if(map.containsValue("details")){
            criteria.setBeforePermit(map.get("old").toString());
            criteria.setAfterPermit(map.get("new").toString());
            criteria.setIsDetails("1");
            criteria.setRemark("更新需求描述：" );
        }else if(map.containsValue("attachmentStr")){
            criteria.setBeforePermit(map.get("old").toString());
            criteria.setAfterPermit(map.get("new").toString());
            criteria.setRemark("附件：" + criteria.getBeforePermit() + criteria.getAfterPermit());
        }else if(map.containsValue("testerStr")){
            criteria.setBeforePermit(map.get("old").toString());
            criteria.setAfterPermit(map.get("new").toString());
            criteria.setRemark("测试人：" + criteria.getBeforePermit() + criteria.getAfterPermit());
        }else if(map.containsValue("developerStr")){
            criteria.setBeforePermit(map.get("old").toString());
            criteria.setAfterPermit(map.get("new").toString());
            criteria.setRemark("开发人：" + criteria.getBeforePermit() + criteria.getAfterPermit());
        }else if(map.containsValue("developResponsibleName")){
            criteria.setBeforePermit(map.get("old").toString());
            criteria.setAfterPermit(map.get("new").toString());
            criteria.setRemark("开发负责人姓名：" + criteria.getBeforePermit() + criteria.getAfterPermit());
        }else if(map.containsValue("testResponsibleName")){
            criteria.setBeforePermit(map.get("old").toString());
            criteria.setAfterPermit(map.get("new").toString());
            criteria.setRemark("测试负责人姓名：" + criteria.getBeforePermit() + criteria.getAfterPermit());
        }else if(map.containsValue("projectNumber")){
            criteria.setBeforePermit(map.get("old").toString());
            criteria.setAfterPermit(map.get("new").toString());
            criteria.setRemark("项目编码：" + criteria.getBeforePermit() + criteria.getAfterPermit());
        }else if(map.containsValue("planOnlineVersion")){
            criteria.setBeforePermit(map.get("old").toString());
            criteria.setAfterPermit(map.get("new").toString());
            criteria.setRemark("计划上线版本：" + criteria.getBeforePermit() + criteria.getAfterPermit());
        }
        /*
         * 新字段 since 2017-07-26 17:24:53
         */
        else if(map.containsValue("estimateTestWorkload")){
        	criteria.setBeforePermit(map.get("old").toString());
            criteria.setAfterPermit(map.get("new").toString());
            criteria.setRemark("预估测试工作量：" + criteria.getBeforePermit() + criteria.getAfterPermit());
        }else if(map.containsValue("expectTestFinishTime")){
        	
        	this.handleDate(map,criteria);//时间格式特殊处理
        	
            criteria.setRemark("测试计划完成时间：" + criteria.getBeforePermit() + criteria.getAfterPermit());
        }else if(map.containsValue("expectTestStartTime")){

        	this.handleDate(map,criteria);//时间格式特殊处理
        	
            criteria.setRemark("测试计划开始时间：" + criteria.getBeforePermit() + criteria.getAfterPermit());
        }
        return criteria;
    }
    
    /**
     * <li>@Description:服务于 ChangeHistoryCriteria 方法
     * <li>
     * <li>创建人：xujiahong
     * <li>创建时间：2017年7月26日
     * <li>修改人：
     * <li>修改时间：
     */
    private void handleDate(Map<String,Object> map,ChangeHistoryCriteria criteria){
//    	System.out.println(map);
//    	System.out.println(map.get("old").toString());
//    	System.out.println(map.get("new").toString());
//    	{new====修改后：Thu Aug 10 00:00:00 CST 2017, old====修改前：空, name=expectFinishTime}
//    	===修改前：空
//    	===修改后：Thu Aug 10 00:00:00 CST 2017
    	
    	String str = map.get("old").toString();
    	logger.info("【修改前的str】："+str);
    	String substring = str.substring(7, str.length());//形如:Thu Aug 10 00:00:00 CST 2017
    	String sub = str.substring(0,7);//===修改前：
    	if(!substring.equals("空")){
    		if(StringUtil.isEmpty(substring)){
    			criteria.setBeforePermit(sub);
    		}else{
    			logger.info(substring);
    			try{
    				String dateStr = formate.format(new Date(substring)).toString();
        			criteria.setBeforePermit(sub + ("1970-01-01".equals(dateStr)?"空":dateStr));
    			}catch(Exception e){
    				logger.error("更新排期-插入历史，处理时间发生异常");
    				e.printStackTrace();
    				criteria.setBeforePermit(sub+"空");
    			}
    		}
    	}else{
    		criteria.setBeforePermit(map.get("old").toString());
    	}
        
    	String strs = map.get("new").toString();//===修改后：Thu Aug 10 00:00:00 CST 2017
    	logger.info("【修改后的strs】："+strs);
    	String subs = strs.substring(0,7);//===修改后：
    	String substrings = strs.substring(7, strs.length());//形如:Thu Aug 10 00:00:00 CST 2017
    	if(!substrings.equals("空")){
    		if(StringUtil.isEmpty(substrings)){
    			criteria.setAfterPermit(subs);
    		}else{
    			logger.info(substrings);
    			try{
    				String dateStr = formate.format(new Date(substrings)).toString();//报错？？？
    				criteria.setAfterPermit(subs + ("1970-01-01".equals(dateStr)?"空":dateStr));
    			}catch(Exception e){
    				logger.error("更新排期-插入历史，处理时间发生异常");
    				e.printStackTrace();
    				criteria.setAfterPermit(subs+"空");
    			}
    		}
    	}else{
    		criteria.setAfterPermit(map.get("new").toString());
    	}
    }

    @Override
    public ChangeHistoryResponse selectChangeHistoryDOList(ChangeHistoryCriteria criteria) {
        FunctionRequireDO fundo = functionRequireDAO.selectByChangeHistory(Long.toString(criteria.getFunctionRequireId()));
        List<ChangeHistoryDO> chList = changeHistoryDO.selectChangeHistoryDOList(fundo.getRequireId());
        List<ChangeHistoryDO> cb = new ArrayList<ChangeHistoryDO>();
        Map<String, String> lineNumber = new HashMap<String, String>();
        for (ChangeHistoryDO changeHistoryDO : chList) {
            if(!StringUtil.isEmpty(changeHistoryDO.getBaselineVersion())){
                lineNumber.put(changeHistoryDO.getBaselineVersion(), "");
            }else{
                lineNumber.put("新建功能需求", "");
            }
        }
        List<BaselineResponse> mapBase = new ArrayList<BaselineResponse>();
        for (String line : lineNumber.keySet()){
            List<ChangeHistoryDO> chNew = new ArrayList<ChangeHistoryDO>();
            for (ChangeHistoryDO chl : chList) {
                if(!StringUtil.isEmpty(chl.getBaselineVersion())){
                    if(chl.getBaselineVersion().equals(line)){
                        chNew.add(chl);
                    }
                }else{
                    if(line.equals("新建功能需求")){
                        chNew.add(chl);
                    }
                }
            }
            BaselineResponse br = new BaselineResponse();
            br.setBaselineVersion(line);
            br.setBaselineList(chNew);
            mapBase.add(br);
        }
        ChangeHistoryResponse chr = new ChangeHistoryResponse();
        chr.setChangeHistoryList(mapBase);
        return chr;
    }

}
